package com.shopping_back.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.pojo.dto.PageDTO;
import com.shopping_back.pojo.entity.Category;
import com.shopping_back.mapper.CategoryMapper;
import com.shopping_back.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 商品类目表 服务实现类
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    // =========== 分页 ===========
    @Override
    public PageDTO<Category> pageCategory(int pageNum, int pageSize, String keyword) {

        LambdaQueryWrapper<Category> qw = Wrappers.<Category>lambdaQuery()
                .like(StringUtils.hasText(keyword), Category::getName, keyword)
                .orderByAsc(Category::getSortOrder);

        Page<Category> page = this.page(new Page<>(pageNum, pageSize), qw);

        PageDTO<Category> dto = new PageDTO<>();
        dto.setList(page.getRecords());
        dto.setTotal(page.getTotal());
        dto.setCurrentPage((int) page.getCurrent());
        dto.setPageSize((int) page.getSize());
        return dto;
    }

    // =========== 新增 ===========
    @Override
    @Transactional
    public void createCategory(Category category) {
        // 固定一级
        category.setParentId(0L);
        category.setLevel(1);

        checkDuplicateName(category.getName(), null);
        this.save(category);
    }

    // =========== 修改 ===========
    @Override
    @Transactional
    public void updateCategory(Category category) {
        // 不允许改 parent / level
        category.setParentId(0L);
        category.setLevel(1);

        checkDuplicateName(category.getName(), category.getId());
        this.updateById(category);
    }

    // =========== 删除 ===========
    @Override
    @Transactional
    public void deleteCategory(Long id) {
        this.removeById(id);
    }

    // =========== 工具 ===========
    private void checkDuplicateName(String name, Long excludeId) {
        long cnt = this.count(Wrappers.<Category>lambdaQuery()
                .eq(Category::getParentId, 0L)
                .eq(Category::getName, name)
                .ne(excludeId != null, Category::getId, excludeId));

        if (cnt > 0) {
            throw new IllegalArgumentException("分类名称已存在");
        }
    }
}
